package cn.wit.summit.chwan.adapters;

import android.content.ClipData;
import android.content.Context;
import android.graphics.Color;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;
import java.util.List;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.dto.CommentBaseBean;
import cn.wit.summit.chwan.models.dto.CommentDetailBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.DateUtils;
import cn.wit.summit.chwan.utils.ForumUtil;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.utils.UtilsMy;
import cn.wit.summit.chwan.widgets.CopyTextView;
import cn.wit.summit.chwan.widgets.VipView;

import static android.content.Context.CLIPBOARD_SERVICE;

/**
 * Created by hezl on 2015/8/12.
 */
public class CommentDetailAdapter extends BaseAdapter {

    //region common
    public enum ViewType {
        DELETED,
        TITLE,
        COMMENT,
        REPLY
    }

    public static class ViewBean {
        ViewType viewType;
        Object obj;

        public ViewBean() {
        }

        public ViewBean(ViewType viewType, Object obj) {
            this.viewType = viewType;
            this.obj = obj;
        }

        public ViewType getViewType() {
            return viewType;
        }

        public void setViewType(ViewType viewType) {
            this.viewType = viewType;
        }

        public Object getObj() {
            return obj;
        }

        public void setObj(Object obj) {
            this.obj = obj;
        }

        public static class Comment {
            public CommentBaseBean data;

            public Comment(CommentBaseBean data) {
                this.data = data;
            }
        }

        public static class Reply {
            public String commentId;
            public CommentBaseBean commentBean;
            public int myAuth;
            public boolean showDivider;
            public int replyItemIndex;
            public boolean lastIndex;
            public boolean hideBottom;

            public Reply(String commentId, CommentBaseBean commentBean, int myAuth, boolean showDivider) {
                this.commentId = commentId;
                this.commentBean = commentBean;
                this.myAuth = myAuth;
                this.showDivider = showDivider;
            }
        }
    }

    private Context mContext;
    private List<ViewBean> itemBeans;

    public CommentDetailAdapter(Context mContext, List<ViewBean> itemBeans, Listener mListenr) {
        this.mContext = mContext;
        this.itemBeans = itemBeans;
        this.mListenr = mListenr;
    }

    public CommentDetailAdapter(Context mContext) {
        this.mContext = mContext;
        itemBeans = new ArrayList<ViewBean>();
    }

//    public void setChildItem (int po) {
//        ViewBean.Reply item = (ViewBean.Reply) getItem(position);
//    }

    @Override
    public int getCount() {
        if (itemBeans != null) {
            return itemBeans.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (itemBeans != null) {
            if (position>=itemBeans.size())
                return null;
            else
                return itemBeans.get(position).getObj();
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        return ViewType.values().length;
    }

    @Override
    public int getItemViewType(int position) {
        if (this.itemBeans != null) {
            ViewBean bean = this.itemBeans.get(position);
            return bean.getViewType().ordinal();
        }
        return -1;
    }

    public List<ViewBean> getItemBeans() {
        return itemBeans;
    }

    public void setItemBeans(List<ViewBean> itemBeans) {
        if (itemBeans == null) return;
        if (this.itemBeans == null) itemBeans = new ArrayList<ViewBean>();

        this.itemBeans.clear();
        this.itemBeans.addAll(itemBeans);
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }
    //endregion

    //region getView
    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {

        int type = getItemViewType(position);

        if (type == ViewType.COMMENT.ordinal()) {
            view = getCommentView(position, view, viewGroup, 2);
        } else if (type == ViewType.TITLE.ordinal()) {
            view = getCommentView(position, view, viewGroup, 1);
        } else if (type == ViewType.REPLY.ordinal()) {
            view = getReplyView(position, view, viewGroup);
        } else if (type == ViewType.DELETED.ordinal()) {
            view = getDeletedView(position, view, viewGroup);
        }

        return view;
    }

    private View getReplyView(int position, View convertView, ViewGroup viewGroup) {
        ReplyViewHolder holder;

        try {
            if (convertView != null) {
                holder = (ReplyViewHolder) convertView.getTag();
            } else {
                holder = new ReplyViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.detail_comment_activity_item_comment_message_reply, null);
                holder.replyContainerV = (LinearLayout) convertView.findViewById(R.id.comment_reply_container);
                holder.replyDividerV = convertView.findViewById(R.id.comment_reply_divider);
                holder.replyContentV = (TextView) convertView.findViewById(R.id.comment_reply_content);
                holder.replyMoreV = (TextView) convertView.findViewById(R.id.comment_reply_more);
                holder.lineV = convertView.findViewById(R.id.line);
                holder.bottomV = convertView.findViewById(R.id.bottom);

                convertView.setTag(holder);
            }
            ViewBean.Reply item = (ViewBean.Reply) getItem(position);
            if (item == null) return convertView;
            if (item.commentBean == null) return convertView;

            if (item.showDivider) {
                holder.replyDividerV.setVisibility(View.VISIBLE);
            } else {
                holder.replyDividerV.setVisibility(View.GONE);
            }

            if (!item.hideBottom) {
                holder.lineV.setVisibility(View.VISIBLE);
                holder.bottomV.setVisibility(View.VISIBLE);
            } else {
                holder.lineV.setVisibility(View.GONE);
                holder.bottomV.setVisibility(View.GONE);
            }

            List<CommentBaseBean.SubCommentBean> replyList = item.commentBean.getSub_comment();
            if (replyList != null && replyList.size() != 0) {
                processCommentReply(holder.replyContainerV, item, true, position);
            } else {
                holder.replyContainerV.removeAllViews();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return convertView;
    }

    public View getCommentView(int position, View view, ViewGroup viewGroup, int type) {
        ViewBean.Comment viewBean = (ViewBean.Comment) getItem(position);
        CommentViewHolder holder = null;
        ViewHolder2 viewHolder2 = null;

        if (view == null) {
            switch (type) {
                case 1:
                    viewHolder2 = new ViewHolder2();
                    view = LayoutInflater.from(mContext).inflate(R.layout.gameinformation_comment_item_title, null);
                    viewHolder2.title = (TextView) view.findViewById(R.id.title);
                    view.setTag(viewHolder2);
                    break;
                case 2:
                    holder = new CommentViewHolder();
                    view = LayoutInflater.from(mContext).inflate(R.layout.detail_commit_item_new_layout, null);
                    holder.main = (RelativeLayout) view.findViewById(R.id.main);
                    holder.userIcon = (SimpleDraweeView) view.findViewById(R.id.usericon);
                    holder.parise = (ImageView) view.findViewById(R.id.parise);
                    holder.userName = (TextView) view.findViewById(R.id.username);
                    holder.time = (TextView) view.findViewById(R.id.time);
                    holder.message = (CopyTextView) view.findViewById(R.id.content);
                    holder.pariseNumber = (TextView) view.findViewById(R.id.pariseNumber);
                    holder.line0 = view.findViewById(R.id.line0);
                    view.setTag(holder);

                    break;
            }
        } else {
            switch (type) {
                case 1:
                    viewHolder2 = (ViewHolder2) view.getTag();
                    break;
                case 2:
                    holder = (CommentViewHolder) view.getTag();
                    break;
            }
        }

        if (viewBean==null) return view;

        CommentBaseBean commitDataBean = viewBean.data;
        switch (type) {
            case 1:
                break;
            case 2:

                if (viewBean == null) return null;
                long timel = Long.parseLong(commitDataBean.getAdd_times() + "000");
                holder.time.setText(DateUtils.FormatForDownloadTime(timel));

                String tempStr = commitDataBean.getContent();
                if (tempStr.contains(":") && !tempStr.endsWith(":"))
                    tempStr = tempStr.split(":")[1];
                holder.message.setText(tempStr);
                final CommentViewHolder finalHolder = holder;
                holder.message.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        String str = "";
                        if (android.os.Build.VERSION.SDK_INT > 11) {
                            android.content.ClipboardManager c = (android.content.ClipboardManager) mContext.getSystemService(CLIPBOARD_SERVICE);
                            c.setPrimaryClip(ClipData.newPlainText("wufan", finalHolder.message.getText()));
                            str = c.getText().toString();
                        } else {
                            android.text.ClipboardManager c = (android.text.ClipboardManager) mContext.getSystemService(CLIPBOARD_SERVICE);
                            c.setText(finalHolder.message.getText());
                            str = c.getText().toString();
                        }
                        String temp = finalHolder.message.getText().toString();
                        if (str.equals(temp))
                            ToastUtils.getInstance(mContext).showToastSystem("已复制到剪贴板！");
                        return false;
                    }
                });

                holder.pariseNumber.setText(commitDataBean.getPraise_count() + "");
                if (commitDataBean.getIs_praise()==1) {
                    holder.parise.setImageResource(R.drawable.uped_ic);
                } else {
                    holder.parise.setImageResource(R.drawable.up_ic);
                }
                    UtilsMy.setIconImage(mContext, commitDataBean.getHead_portrait(), holder.userIcon);

                holder.userName.setText(Html.fromHtml(commitDataBean.getUser_name()));

                if (position==0)
                    holder.line0.setVisibility(View.GONE);
                else
                    holder.line0.setVisibility(View.VISIBLE);
                setOnPraiseListener(holder.parise, holder.pariseNumber, commitDataBean, position);
                setOnReplyListener(view, commitDataBean, position, holder.message);
                break;
        }
        return view;
    }

    public View getDeletedView(int position, View view, ViewGroup viewGroup) {
        DeletedViewHolder holder = null;
        view = LayoutInflater.from(mContext).inflate(R.layout.comment_detail_deleted_view, null);
        return view;
    }
    //endregion

    //region ViewHolder
    class ViewHolder {

    }

    class ViewHolder2 {
        private TextView title;
    }

    class DeletedViewHolder extends ViewHolder {
    }

    class CommentViewHolder extends ViewHolder {
        private RelativeLayout main;
        private SimpleDraweeView userIcon;
        private ImageView parise;
        private TextView userName;
        private TextView time;
        private CopyTextView message;
        private TextView pariseNumber;
        public View line0;
    }

    class ReplyViewHolder extends ViewHolder {
        public LinearLayout replyContainerV;
        public View replyDividerV;
        public TextView replyContentV;
        public TextView replyMoreV;
        public View lineV;
        public View bottomV;
    }
    //endregion

    //region 事件回调
    Listener mListenr = null;

    public Listener getmListenr() {
        return mListenr;
    }

    public void setListenr(Listener mListenr) {
        this.mListenr = mListenr;
    }

    public interface Listener {

        void onPraise(CommentBaseBean bean, int position, int type);

        void onReplyReply(CommentBaseBean.SubCommentBean sub, int pn, String id);

        void onReply(CommentBaseBean bean, int position);
    }

    /**
     * 防止快速点击,启动多个同样的界面
     *
     * @return
     */
    long lastClickTime;
    public boolean isFastDoubleClick() {
        long now = System.currentTimeMillis();
        long timeD = now - lastClickTime;
        lastClickTime = now;
        return timeD <= 500;
    }

    private void setOnPraiseListener(View view, final TextView tv, final CommentBaseBean commitDataBean, final int position) {
        view.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

//                if (AccountUtil_.getInstance_(mContext).isTourist()) {
//                    DialogUtil_.getInstance_(mContext).getAccountLoginDialogForCommon(mContext,
//                            mContext.getResources().getString(R.string.comment_login_tx), "登录", "取消", null);
//                    return;
//                }
                if (isFastDoubleClick()) return;
                if (AccountUtil.getInstance().getUid()==0) {
                    IntentUtil.getInstance().goLoginActivity(mContext);
                    return;
                }
                if (commitDataBean==null)
                    return;
                if (commitDataBean.getIs_praise()==1) {
                    subPraise(position);
                    ImageView view = (ImageView) v;
                    view.setImageResource(R.drawable.up_ic);
                    if (mListenr != null) {
                        mListenr.onPraise(commitDataBean, position, 2);
                    }
                    return;
                } else {
                    commitDataBean.setIs_praise(1);
                }

                if (AccountUtil.getInstance().getAccountData() != null) {
                    ImageView view = (ImageView) v;
                    view.setImageResource(R.drawable.uped_ic);
                    Animation scaleAnim = AnimationUtils.loadAnimation(mContext, R.anim.scale_reset);
                    v.startAnimation(scaleAnim);
                    scaleAnim.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            long num = Long.valueOf(tv.getText().toString());
                            tv.setText((num+1)+"");
                            addPraise(position);

                            if (mListenr != null) {
                                mListenr.onPraise(commitDataBean, position, 1);
                            }
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                } else {
//                    IntentUtil.getInstance().goMyAccountLoginActivity(mContext, 0, 2);
                    IntentUtil.getInstance().goLoginInteractive(mContext);
                }
            }
        });
    }

    public void addPraise(int position) {
        ViewBean.Comment viewBean = (ViewBean.Comment) getItem(position);

        if (viewBean==null) return;

        long num = Long.valueOf(viewBean.data.getPraise_count());
        viewBean.data.setIs_praise(1);
        viewBean.data.setPraise_count(num+1);
        notifyDataSetChanged();
    }

    public void subPraise(int position) {
        ViewBean.Comment viewBean = (ViewBean.Comment) getItem(position);

        if (viewBean==null) return;

        long num = Long.valueOf(viewBean.data.getPraise_count());
        viewBean.data.setIs_praise(0);
        if (num-1<0)
            viewBean.data.setPraise_count(0);
        else
            viewBean.data.setPraise_count(num-1);
        notifyDataSetChanged();
    }

    public void resetPraise(int position) {
        ViewBean.Comment viewBean = (ViewBean.Comment) getItem(position);

        if (viewBean==null) return;

        long num = Long.valueOf(viewBean.data.getPraise_count());
        if (viewBean.data.getIs_praise()==1) {
            viewBean.data.setIs_praise(0);
            if (num-1<0)
                viewBean.data.setPraise_count(0);
            else
                viewBean.data.setPraise_count(num-1);
        } else {
            viewBean.data.setIs_praise(1);
            viewBean.data.setPraise_count(num+1);
        }
        notifyDataSetChanged();
    }

    private void setOnCommentReplyReply(View view, final CommentBaseBean.SubCommentBean sub
            , final int pn, final int position) {
        view.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String po = "";
                for (int i=position;i>=0;i--) {
                    if (itemBeans.get(i).getViewType()==ViewType.COMMENT) {
                        ViewBean.Comment temp = (ViewBean.Comment) itemBeans.get(i).getObj();
                        po = temp.data.getId();
                        break;
                    }
                }
                if (mListenr != null) {
                    mListenr.onReplyReply(sub, pn, po);
                }
            }
        });
    }

    private void setOnReplyListener(View view, final CommentBaseBean commitDataBean
            , final int position, final CopyTextView message) {
        view.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mListenr != null) {
                    mListenr.onReply(commitDataBean, position);
                }
                message.clearFocus();
            }
        });
    }

    //endregion

    //region 评论回复
    private void processCommentReply(final View parent, final ViewBean.Reply commentMessageReply, boolean hideMore, final int position) {
        final String cid = commentMessageReply.commentId;
        final int itemIndex = commentMessageReply.replyItemIndex;
        final boolean lastIndex = commentMessageReply.lastIndex;
        final CommentBaseBean forumCommentBean = commentMessageReply.commentBean;
        final List<CommentBaseBean.SubCommentBean> reply_list = forumCommentBean.getSub_comment();
        ((LinearLayout) parent).removeAllViews();
        int morePosition = 3;

        final int size = reply_list.size();
        for (int i = 0; i < size + 1; i++) {
            if (i > morePosition && hideMore) continue;

            View view = LayoutInflater.from(mContext).inflate(R.layout.comment_reply_item, null);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            view.setLayoutParams(params);

            TextView content = (TextView) view.findViewById(R.id.comment_reply_content);
            TextView more = (TextView) view.findViewById(R.id.comment_reply_more);

            if (i == size && size > morePosition || (itemIndex > 0 && lastIndex && i == size)) {
                content.setVisibility(View.GONE);
                more.setVisibility(View.VISIBLE);
                more.setText("收起");
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        processCommentReply(parent, commentMessageReply, true, position);

                        if (itemIndex == 0) return;
                        CommentBaseBean forumCommentBean = new CommentBaseBean();
                        List<CommentBaseBean.SubCommentBean> replyBeanList = new ArrayList<>();
                        for (int j = itemIndex; j >= 0; j--) {
                            ViewBean viewBean = itemBeans.get(position - j);
                            ViewBean.Reply commentMessageReply1 = null;
                            if (viewBean.getViewType() == ViewType.REPLY) {
                                commentMessageReply1 = (ViewBean.Reply) viewBean.getObj();
                            }

                            if (null != commentMessageReply1 && cid == commentMessageReply1.commentId) {
                                replyBeanList.addAll(commentMessageReply1.commentBean.getSub_comment());
                            }
                        }

                        for (int j = 0; j <= itemIndex; j++) {
                            itemBeans.remove(position - j);
                        }

                        forumCommentBean.setSub_comment(replyBeanList);
                        ViewBean viewBean = createCommentMessageReplyViewBean(cid, forumCommentBean, commentMessageReply.myAuth, true);
                        itemBeans.add(position - itemIndex, viewBean);
                        notifyDataSetChanged();

                    }
                });
            } else if (i == morePosition && hideMore && size > morePosition) {
                content.setVisibility(View.GONE);
                more.setVisibility(View.VISIBLE);
                more.setText(more.getResources().getString(R.string.comment_item_content_more, size - morePosition));
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        processCommentReply(parent, commentMessageReply, false, position);

                        int index = 0;
                        boolean isLastIndex = false;
                        List<CommentBaseBean.SubCommentBean> reply_list = null;
                        for (int j = 0; j < size; j += 3) {
                            CommentBaseBean commentBean = new CommentBaseBean(forumCommentBean);
                            reply_list = commentBean.getSub_comment();
                            List<CommentBaseBean.SubCommentBean> list = new ArrayList<>();
                            if (j + 3 < reply_list.size()) {
                                list.addAll(reply_list.subList(j, j + 3));
                            } else {
                                list.addAll(reply_list.subList(j, reply_list.size()));
                                isLastIndex = true;
                            }
                            commentBean.setSub_comment(list);
                            ViewBean obj = createCommentMessageReplyViewBean(cid, commentBean, commentMessageReply.myAuth, index == 0);
                            ViewBean.Reply commentMessageReply1 = (ViewBean.Reply) obj.getObj();
                            commentMessageReply1.replyItemIndex = index;
                            commentMessageReply1.lastIndex = isLastIndex;
                            commentMessageReply1.showDivider = (index == 0);
                            setCommentMessageReplyBottomVisibility(obj, !isLastIndex);
                            itemBeans.add(position + index + 1, obj);
                            index++;
                        }
                        itemBeans.remove(position);
                        notifyDataSetChanged();
                    }
                });
            } else {
                if (i >= size || (i >= morePosition && hideMore))
                    continue;

                content.setVisibility(View.VISIBLE);
                more.setVisibility(View.GONE);
                final CommentBaseBean.SubCommentBean item = reply_list.get(i);
                String s = item.getContent();
                try {
                    String fromName = item.getUser_name()+" ";
                    String  toName = "";
                    if (s.contains(":")){
                        String[] tempStrOne = s.split(":");
                        if (tempStrOne.length==2) {
                            if (tempStrOne[0].contains("@")) {
                                String[] tempStr = tempStrOne[0].split("@");
                                if (!tempStr[1].equals("")) {
                                    toName = " "+tempStr[1];
                                }
                            }
                            ForumUtil.setCommentReplyVipText(content, fromName, item.getVip_level()
                                    , item.getSvip_level(), toName, item.getReply_vip_level()
                                    , item.getReply_svip_level(), tempStrOne[1]);
                        } else {
                            ForumUtil.setCommentReplyVipText(content, fromName, item.getVip_level()
                                    , item.getSvip_level(), toName, item.getReply_vip_level()
                                    , item.getReply_svip_level(), s);
                        }
                    } else {
                        ForumUtil.setCommentReplyVipText(content, fromName, item.getVip_level()
                                , item.getSvip_level(), toName, item.getReply_vip_level()
                                , item.getReply_svip_level(), s);
                    }

                    setOnCommentReplyReply(view, item, forumCommentBean.getPn(), position);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


            ((LinearLayout) parent).addView(view);
        }
    }

    ViewBean createCommentMessageReplyViewBean(String pid, CommentBaseBean bean, int myAuth, boolean showDivider) {
        ViewBean viewBean = new ViewBean(ViewType.REPLY, new ViewBean.Reply(
                pid,
                bean,
                myAuth,
                showDivider
        ));
        return viewBean;
    }

    void setCommentMessageReplyBottomVisibility(ViewBean bean, boolean hideBottom) {
        if (bean == null) return;
        try {
            ViewBean.Reply commentMessageReply = (ViewBean.Reply) bean.getObj();
            commentMessageReply.hideBottom = hideBottom;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //endregion

}
